import COS from 'cos-wx-sdk-v5';
import store from '../store/index.js'

const cos = new COS({
	SecretId: 'AKIDdEnEYyLk7IF6m9RdjvEj7Pcu8E8vEXot',
	SecretKey: 'zvhU9f3Hi3IPNCtTuqjZJvOn4ExiFZfa',
});

const Bucket = 'golfren-1322973459'
const Region = 'ap-beijing'
const prefix = 'wx-mini'
export const today = () => {
	const currentDate = new Date();
	const year = currentDate.getFullYear();
	const month = String(currentDate.getMonth() + 1).padStart(2, '0');
	const day = String(currentDate.getDate()).padStart(2, '0');
	return `${year}${month}${day}`;
};

export const ossUpload = (filePath) => {
	return new Promise((resolve, reject) => {
		const originalFileName = filePath.split('/').pop(); // 获取原始文件名
		const timestamp = new Date().getTime(); // 获取时间戳
		const day = today()
		
		const fileName = `/img/${day}/${timestamp}-${originalFileName}`; // 生成唯一文件名
		// 上传文件
		cos.postObject({
			Bucket,
			/* 必须 */
			Region,
			/* 必须 */
			Key: prefix + fileName,
			/* 必须 */
			FilePath: filePath,
			/* 必须 */
			onProgress: function(info) {
				console.log('进度',info, JSON.stringify(info));
				// 更新提示内容
				uni.showToast({
					title: `上传中: ${Math.floor(info.percent * 100)}%`,
					icon: 'loading',
					duration: 10000, // 继续显示提示
					mask: true
				});
			}
		}, function(err, data) {
			uni.hideToast()
			if (err) {
				console.log('上传失败',err);
				reject(err)
			} else {
				console.log('上传成功', data);
				resolve({
					name: originalFileName,
					url: store.state.ossurl + fileName
				})
			}
		});
	})
}

export const ossDel = (url) => {
	let fileUrl = url.replace(store.state.ossurl,'')
	console.log('删除', fileUrl)
	return new Promise((resolve,reject) => {
		// 删除文件
		cos.deleteObject({
		  Bucket,
		  Region,
		  Key: prefix + fileUrl
		}, function(err, data) {
		  if (err) {
		    console.error('删除文件失败:', err);
			reject()
		  } else {
		    console.log('文件删除成功:', data);
			resolve()
		  }
		});
	})
	
}